﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace System.Windows.Forms
{
    /// <summary>
    /// 表示带有边距的多行文本框
    /// </summary>
    public partial class MarginTextBox : PlaceHolderTextBox
    {
        /// <inheritdoc cref="TextBoxBase.Padding"/>
        [Browsable(true)]
        [Category("Xejen")]
        [Description("表示文本的边距")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public Padding TextPadding { get; set; }

        /// <inheritdoc cref="MarginTextBox"/>
        public MarginTextBox()
        {
            this.Multiline = true;
            this.WordWrap = true;
        }

        /// <inheritdoc/>
        protected override void OnVisibleChanged(EventArgs e)
        {
            base.OnVisibleChanged(e);

            this.Align();
        }

        /// <inheritdoc/>
        protected override void WndProc(ref System.Windows.Forms.Message m)
        {
            //0x0302是粘贴消息
            if (m.Msg == 0x0302)
            {
                //这里要做位置索引限制
                this.Text = Clipboard.GetText(TextDataFormat.Text);

                //拦截此消息
                m.Result = IntPtr.Zero;
                return;
            }

            //若此消息不是粘贴消息，则交给其基类去处理
            base.WndProc(ref m);
        }

        /// <inheritdoc/>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public override string Text
        {
            get
            {
                return base.Text;
            }
            set
            {
                base.Text = value;
            }
        }

        [DllImport("user32.dll", EntryPoint = "SendMessageA")]
        private static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, ref Rectangle lParam);

        private const int EM_GETRECT = 0xB2;
        private const int EM_SETRECTNP = 0xB4;

        /// <summary>
        /// 对齐
        /// </summary>
        private void Align()
        {
            TextBox text = this;
            if (text.Multiline == false)
            {
                return;
            }

            Rectangle rc = new Rectangle();
            SendMessage(text.Handle, EM_GETRECT, IntPtr.Zero, ref rc);
            //文字的大小
            Size size = TextRenderer.MeasureText(" ", text.Font);

            rc.X = TextPadding.Left;
            rc.Y = TextPadding.Right;
            rc.Width = this.Width - TextPadding.Left - TextPadding.Right;
            rc.Height = this.Height - TextPadding.Top - TextPadding.Bottom;

            SendMessage(text.Handle, EM_SETRECTNP, IntPtr.Zero, ref rc);

            base.Position = rc;

            text.Refresh();
        }
    }
}